<?php
class XA_Tree {


	public static function depthList($tree, $depth = 0) {
		$return = array();
		if (!empty($tree)) {
			foreach ($tree as $id => $item) {
				$return[$id] = $item + array('depth' => $depth);
				if (isset($item['child_list'])) {
					$return += self::depthList($item['child_list'], $depth + 1);
					unset($return[$id]['child_list']);
				}
			}
		}
		return $return;
	}


	public static function delNode(&$tree, $node_id, $children = false) {
		foreach ($tree as $id => $node) {
			if ($id == $node_id) {
				if ($children) {
					unset($tree[$id]['child_list']);
				} else {
					unset($tree[$id]);
				}
				return true;
			} elseif (!empty($tree[$id]['child_list'])) {
				if (self::delNode($tree[$id]['child_list'], $node_id, $children)) {
					return true;
				}
			}
		}
		return false;
	}


	public static function get($list, $parent_name = 'parent_id') {
		$tree = array();
		foreach ($list as $id => $item) {
			$parent_id = $item[$parent_name];
			if ($parent_id && isset($list[$parent_id])) {
				$list[$parent_id]['child_list'][$id] = &$list[$id];
			} else {
				$tree[$id] = &$list[$id];
			}
		}
		return $tree;
	}
}
